<script setup lang="ts">
  import { Ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { unitType } from '@/types';
  import { getdomainList, getUnitList, getTreeList } from '@/api/Unitregein';
  import {
    iconsDataJson,
    rightMenuList,
    numberValue,
    dataTree,
    iconsDataSourceJson,
    rightSourceMenuList,
    iconsDataEnumJson,
    rightEnumList,
    iconsDataCataAccessJson,
    rightCataAccessList,
    iconsDataSqlJson,
    rightSqlList,
  } from './index';
  const Route = useRoute();
  const containerTree = ref<HTMLElement | null>(null);
  const selectArrow = ref<any>(null);
  const DomainList = ref<Array<Namespace.RegionObject>>([]);
  const UnitList = ref<Array<Namespace.UnitObject>>([]);
  const TreeList = ref<Array<Namespace.unitTree>>();
  /**
   * 临时保存原始数据
   */
  const temporaryData = ref<Array<Namespace.RegionObject>>([]);

  /**
   * 保存参数
   */
  const parameter = ref<string>('');
  const routerValue = ref<string>('');
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:nameValue', val: string): void;
    (e: 'pcPattern', val: string): void;
    (e: 'phonePattern', val: string): void;
  }
  const props = defineProps({
    data: {
      type: Object,
      default: () => {},
    },
    isCommpand: {
      type: Boolean,
      default: false,
    },
    islower: {
      type: Boolean,
      default: false,
    },
    pattern: {
      type: String,
      default: 'pc',
    },
  });
  const UnitData = ref<unitType>({
    Domain: '',
    Unit: '',
  });
  const commandData = ref<{
    Unit: string;
  }>({
    Unit: '',
  });
  const selectCommandData = ref<{ value: string; label: string }[]>([]);
  const iconsData = ref<Array<object>>();
  const rightMenuRef = ref<any>();
  onMounted(async () => {
    if (props.islower) {
      parameter.value = '3';
      routerValue.value = '数据权限';
      iconsData.value = iconsDataCataAccessJson;
      // rightMenuRef.value = rightCataAccessList;
      getDomain();
    } else {
      switch (Route.name) {
        case 'root':
          parameter.value = '1';
          routerValue.value = '单元管理';
          iconsData.value = iconsDataJson;
          rightMenuRef.value = rightMenuList;
          getDomain();
          break;
        case 'sourceDataManage':
          parameter.value = '0';
          routerValue.value = '数据管理';
          iconsData.value = iconsDataSourceJson;
          rightMenuRef.value = rightSourceMenuList;
          getDomain();
          break;
        case 'enumErationDomain':
          parameter.value = '2';
          routerValue.value = '枚举管理';
          iconsData.value = iconsDataEnumJson;
          rightMenuRef.value = rightEnumList;
          getDomain();
          break;
        case 'cataAccess':
          parameter.value = '3';
          routerValue.value = '数据权限';
          iconsData.value = iconsDataCataAccessJson;
          rightMenuRef.value = rightCataAccessList;
          getDomain();
          break;
        case 'commandPages':
          routerValue.value = '单元选择';
          iconsData.value = iconsDataJson;
          getTreeData(props.data.regionId);
          break;
        case 'sqlManagement':
          parameter.value = '4';
          routerValue.value = '功能sql管理';
          iconsData.value = iconsDataSqlJson;
          rightMenuRef.value = rightSqlList;
          getDomain();
          break;
        default:
          break;
      }
    }
  });
  const getDomain = async () => {
    const { data } = await getdomainList(parameter.value);
    const dataList = data.map((it) => {
      return {
        label: it.regionCode + '(' + it.regionName + ')',
        value: it.regionId as number,
      };
    });
    DomainList.value = dataList as unknown as Array<Namespace.RegionObject>;
    temporaryData.value = data;
    UnitData.value.Domain = DomainList.value[0].value;
    const dataFilter = data.filter((item) => {
      return (item.regionId as unknown as string) == UnitData.value.Domain;
    });
    emit('update:nameValue', dataFilter[0].regionCode as string);
    getUnitData();
  };
  const handleChangeLabel = (value: string) => {
    const data = temporaryData.value.filter((item) => {
      return (item.regionId as unknown as string) == value;
    });
    emit('update:nameValue', data[0].regionCode as string);
  };
  const sendGrandson = inject('sendHandle') as Function;
  const flattenData = (node, flattenedData) => {
    if (node.children && node.children.length > 0) {
      selectCommandData.value.push({ value: node.id, label: node.text });
      for (const child of node.children) {
        flattenData(child, flattenedData);
      }
    } else {
      selectCommandData.value.push({ value: node.id, label: node.text });
    }
  };
  const getTreeData = async (value: number) => {
    const { data } = await getTreeList(value);
    TreeList.value = [data];
    if (Route.name == 'commandPages' && props.isCommpand) {
      selectCommandData.value = [];
      commandData.value.Unit = '';
      sendGrandson(TreeList.value[0]);
      TreeList.value.forEach((node: any) => {
        flattenData(node, selectCommandData.value);
      });
    }
  };

  const sendUnitData = inject('sendUnit') as Function;
  const getUnitData = async () => {
    // Route.name === 'cataAccess' ? '2'  :
    const { data } = await getUnitList({ type: '0' }, UnitData.value.Domain as unknown as number);
    const dataList = data.map((it) => {
      return {
        label:
          it.unitCode && it.unitName
            ? it.unitCode + ' ' + it.unitName + ''
            : it.unitCode
            ? it.unitCode
            : it.unitName,
        value: it.unitId,
      };
    });
    UnitList.value = dataList as unknown as Array<Namespace.UnitObject>;
    sendUnitData(UnitData.value.Domain);
  };
  const change = (item: any) => {
    if (!item) {
      UnitData.value.Unit = '';
      commandData.value.Unit = '';
    }
  };
  watch(
    props.data,
    (value: any) => {
      if (value?.dataId.id && Route.name == 'commandPages' && props.isCommpand) {
        getTreeData(value.regionId);
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  watch(
    () => UnitData.value.Domain,
    async (value: any) => {
      if (value) {
        getTreeData(value);
        UnitData.value.Unit = '';
        getUnitData();
        sendUnitData(UnitData.value.Domain);
      }
    },
    {
      deep: true,
    },
  );
  watch(
    () => props.data.update,
    async (value) => {
      if (value || props.data.code === 0) {
        UnitData.value.Unit = '';
        // getDomain();
        getUnitData();
        getTreeData(UnitData.value.Domain as unknown as number);
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  watch(
    () => numberValue,
    async (value) => {
      if (value || props.data.code === 0) {
        UnitData.value.Unit = '';
        // getDomain();
        getUnitData();
        getTreeData(UnitData.value.Domain as unknown as number);
      }
    },
    {
      deep: true,
    },
  );
  const container = inject<Ref<HTMLElement | null>>('container');
  const hanldeLeftWidth = async () => {
    let width = '300px';
    let padding = '20px';
    let borderTop = '4px solid var(--el-menu-border-color)';
    let borderRight = '1px solid var(--el-menu-border-color)';
    if (container!.value?.style.width == '0px') {
      if (container && container.value) {
        selectArrow.value.style.transform = 'translate(-50%, -50%) rotate(0deg)';
        selectArrow.value.style.left = '20%';
        container.value.style.width = width;
        // containerTree.value!.style.width = width; // 隐藏树形
        containerTree.value!.style.padding = padding;
        containerTree.value!.style.borderTop = borderTop;
        containerTree.value!.style.borderRight = borderRight;
      }
    } else {
      if (container && container.value) {
        selectArrow.value.style.transform = 'translate(-50%, -50%) rotate(180deg)';
        selectArrow.value.style.left = '57%';
        container.value.style.width = '0';
        // containerTree.value!.style.width = '0';  // 隐藏树形
        containerTree.value!.style.padding = '0';
        containerTree.value!.style.borderTop = 'none';
        containerTree.value!.style.borderRight = 'none';
      }
    }
  };
</script>

<template>
  <div class="container">
    <div
      class="select-content"
      ref="containerTree"
      :style="{ borderRight: islower ? 'none' : '1px solid var(--el-menu-border-color)' }"
    >
      <div style="display: flex; justify-content: space-between; align-items: center">
        <span class="title">{{ routerValue }}</span>
        <div style="display: flex; align-items: center">
          <ElButton v-if="pattern == 'pc'" type="text" class="color-red">
            <SvgIcon name="computer-red" size="14" />
            PC端模式
          </ElButton>
          <ElButton v-else type="text" @click="() => $emit('pcPattern', 'pc')">
            <SvgIcon name="computer" size="14" />
            PC端模式
          </ElButton>
          <ElButton v-if="pattern == 'phone'" type="text" class="color-red">
            <SvgIcon name="phone-red" size="14" />
            移动端模式
          </ElButton>
          <ElButton v-else type="text" @click="() => $emit('phonePattern', 'phone')">
            <SvgIcon name="phone" size="14" />
            移动端模式
          </ElButton>
          <!-- <span class="title"><SvgIcon name="computer-red" size="14" />PC端模式</span>
          <span class="title"><SvgIcon name="phone-red" size="14" />移动端模式</span> -->
        </div>
      </div>
      <ElForm :model="UnitData" v-if="!props.isCommpand">
        <ElSelectV2
          filterable
          v-model="UnitData.Domain"
          :options="DomainList"
          style="width: 100%"
          placeholder="请选择"
          size="large"
          @change="handleChangeLabel"
        />
        <ElSelectV2
          filterable
          v-model="UnitData.Unit"
          :options="UnitList"
          style="width: 100%"
          placeholder="请选择单元"
          clearable
          @change="change"
          size="large"
        />
      </ElForm>
      <ElForm :model="commandData" v-else>
        <ElSelectV2
          filterable
          v-model="commandData.Unit"
          :options="selectCommandData"
          style="width: 100%"
          placeholder="请选择单元"
          clearable
          @change="change"
          size="large"
        />
      </ElForm>
      <ElementTree
        :data="TreeList"
        :icons="true"
        :dataTree="dataTree"
        :selected="props.data.selected"
        :id="UnitData.Unit || commandData.Unit"
        :iconsData="iconsData"
        :rightMenuList="rightMenuRef"
        :menuShow="rightMenuRef"
        :isCommpand="props.isCommpand"
        :islower="props.islower"
      />
    </div>
    <div
      class="select-left-arrow"
      v-if="!props.isCommpand && !props.islower"
      @click="hanldeLeftWidth"
    >
      <span ref="selectArrow"></span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .container {
    height: $height;
    position: relative;
    .select-content {
      padding: 20px;
      box-sizing: border-box;
      border-top: 4px solid var(--el-menu-border-color);
      border-right: 1px solid var(--el-menu-border-color);
      height: $height;
      // display: grid;
      // grid-template-rows: 0.8fr 2.8fr 21fr;
      position: relative;
      overflow: hidden;
      .title {
        display: flex;
        margin-bottom: 5px;
      }
    }
    .select-left-arrow {
      position: absolute;
      width: 16px;
      height: 50px;
      top: 50%;
      right: -15px;
      -webkit-transform: translateY(-50%);
      transform: translateY(-50%);
      background-color: transparent;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      z-index: 10;
      cursor: pointer;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -ms-flex-direction: column;
      flex-direction: column;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      justify-content: center;
      span {
        display: block;
        position: absolute;
        width: 0;
        height: 0;
        border-width: 5px;
        border-color: transparent;
        border-right-color: var(--el-menu-border-color);
        border-style: solid;
        left: 20%;
        top: 50%;
        -webkit-mask-size: 100% 100%;
        mask-size: 100% 100%;
        -webkit-mask-repeat: no-repeat;
        mask-repeat: no-repeat;
        -webkit-transform: translate(-50%, -50%) rotate(0deg);
        transform: translate(-50%, -50%) rotate(0deg);
      }
    }
    .select-left-arrow::before {
      content: '';
      position: absolute;
      border-radius: 0 10px 10px 0;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      border-left: 0;
      border-color: var(--el-menu-border-color);
      border-style: solid;
      top: 0;
      right: 0;
      bottom: 0;
      left: 1px;
      background: var(--el-fill-color-blank);
      z-index: -1;
      -webkit-transform: perspective(50px) rotateY(30deg);
      transform: perspective(50px) rotateY(30deg);
      -webkit-transition: all 0.15s;
      transition: all 0.15s;
    }
  }
  .color-red {
    color: red !important;
    :hover {
      color: red !important;
    }
  }
</style>
